package system.student.funtion.exhibition;

import system.student.entity.Course;
import system.student.entity.Score;
import system.student.entity.StudentDetail;
import system.student.entity.login.LoginResponse;
import system.student.entity.signin.SignInTask;
import system.student.entity.updatepassword.UpdatePasswordRequest;
import system.student.entity.updatepassword.UpdatePasswordState;
import system.student.entity.user.Student;
import system.student.entity.user.Teacher;
import system.student.entity.user.UserInfo;
import system.student.funtion.context.UpdatePasswordContext;
import system.student.funtion.exhibition.teacherfunction.CourseService;
import system.student.funtion.exhibition.teacherfunction.SignInService;
import system.student.funtion.exhibition.teacherfunction.impl.CourseServiceImpl;
import system.student.funtion.exhibition.teacherfunction.impl.SignInServiceImpl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class TeacherExhibition {

    //注入课程服务
    private static final CourseService courseService = new CourseServiceImpl();
    private static final SignInService signInService = new SignInServiceImpl();

    public static void runningTeacherExhibition(LoginResponse loginResponse) {
        Teacher user = (Teacher) loginResponse.getUser();
        boolean cur = true;
        while (cur) {
            System.out.println("-------"+user.getName() + "欢迎来到教师页面"+"---------");
            System.out.println("1.查看我的所有课程");//已完成
            System.out.println("2.根据课程号查看所有学生");//已完成
            System.out.println("3.根据课程号和学号给学生打分");//已完成
            System.out.println("4.根据课程号和学号查看某个学生的信息");//已完成
            System.out.println("5.我的信息");//已完成
            System.out.println("6.添加课程");//已完成
            System.out.println("7.设置签到");//已完成
            System.out.println("8.退出");
            System.out.println("9.修改密码");
            Scanner scanner = new Scanner(System.in);
            String option = scanner.next();
            switch (option) {
                case "1":{
                    System.out.println("查看我的所有课程");//已完成
                    List<Course> courseList
                            = courseService.findAllCourseByTeacherId(user.getId());
                    if (courseList == null || courseList.isEmpty()) {
                        System.err.println("暂无课程信息");
                    }else {
                        printCourseList(courseList);
                    }
                }break;
                case "2":{
                    System.out.println("当前你的课程");
                    List<Course> courseList = courseService.findAllCourseByTeacherId(user.getId());
                    printCourseList(courseList);
                    System.out.println("请输入课程id:");
                    Long courseId = scanner.nextLong();
                    Score score = new Score();
                    score.setCourseId(courseId);
                    List<StudentDetail> studentList = courseService.findStudentById(score);
                    printStudentDetails(studentList);
                }break;
                case "3":{
                    System.out.println("根据课程号和学号给学生打分功能");
                    System.out.println("您现在所有的课程");
                    List<Course> courseList = courseService.findAllCourseByTeacherId(user.getId());
                    printCourseList(courseList);
                    System.out.println("请输入你要打分的课程的id");
                    Long courseId = scanner.nextLong();
                    Score score = new Score();
                    score.setCourseId(courseId);
                    List<StudentDetail> studentList = courseService.findStudentById(score);
                    printStudentDetails(studentList);
                    if(studentList.isEmpty()){
                        System.err.println("暂时还没有学生选择这门课");
                        break;
                    }else {
                        System.out.println("请输入学生id");
                        Long studentId = scanner.nextLong();
                        System.out.println("请输入学生成绩");
                        Integer score0 = scanner.nextInt();
                        Score studentScore = new Score(null, studentId, courseId, score0);
                        courseService.updateScore(studentScore);
                    }
                }break;
                case "4":{
                    System.out.println("根据课程id和学生id查看某个学生的信息功能");
                    System.out.println("您现在所有的课程");
                    List<Course> courseList = courseService.findAllCourseByTeacherId(user.getId());
                    printCourseList(courseList);
                    System.out.println("请输入你要查看的课程的id");
                    Long courseId = scanner.nextLong();
                    Score score = new Score();
                    score.setCourseId(courseId);
                    List<StudentDetail> studentList = courseService.findStudentById(score);
                    printStudentDetails(studentList);
                    if (studentList.isEmpty()){
                        System.err.println("暂时还没有学生选择这门课");
                        break;
                    }else {
                        System.out.println("请输入学生id");
                        Long studentId = scanner.nextLong();
                        Score studentScore = new Score();
                        studentScore.setStudentId(studentId);
                        studentScore.setCourseId(courseId);
                        List<StudentDetail> student = courseService.findStudentById(studentScore);
                        // 打印表头
                        System.out.println("+-------+------------+------------+-------+-----------------+----------------------+-----------------+------------+-----------------+");
                        System.out.println("|  ID   | STUDENT_ID | COURSE_ID  | SCORE | TEACHER_NAME    | COURSE_NAME          | STUDENT_NAME    | CLASS_ID   | CLASS_NAME      |");
                        System.out.println("+-------+------------+------------+-------+-----------------+----------------------+-----------------+------------+-----------------+");
                        System.out.println("|"+student.get(0).toString()+"|");
                        // 打印表尾
                        System.out.println("+-------+------------+------------+-------+-----------------+----------------------+-----------------+------------+-----------------+");
                    }
                }break;
                case "5":{
                    System.out.println("我的信息:");
                    String name = user.getName();
                    String department = user.getDepartment();
                    UserInfo userInfo = user.getUserInfo();
                    Teacher  teacher = new Teacher(userInfo, name, department);
                    System.out.println("+-----------------+------------+-----------------+-----------------+");
                    System.out.printf("| %-15s | %-10s | %-15s | %-15s |%n", "Name", "Department", "Username", "Phone");
                    System.out.printf("| %-15s | %-10s | %-15s | %-15s |%n",
                            teacher.getName(),
                            teacher.getDepartment(),
                            teacher.getUserInfo().getUsername(),
                            teacher.getUserInfo().getPhone());
                    System.out.println("+-----------------+------------+-----------------+-----------------+");

                }break;
                case "6":{
                    System.out.println("添加课程");
                    Course course = new Course();
                    System.out.println("输入课程名称");
                    String courseName = scanner.next();
                    course.setCourseName(courseName);
                    course.setTeacherId(user.getId());
                    course.setTeacherName(user.getName());
                    courseService.addCourse(course);
                }break;
                case "7":{
                    Long teacherId = user.getUserId();
                    System.out.println("请输入签到时长, 单位秒");
                    int second = scanner.nextInt();
                    scanner.nextLine();
                    System.out.println("请输入签到名");
                    String taskName = scanner.nextLine();
                    System.out.println("请输入课程id");
                    int courseId = scanner.nextInt();
                    LocalDateTime startTime = LocalDateTime.now();
                    LocalDateTime endTime = startTime.plusSeconds(second);
                    List<Student> studentList = courseService.findAllStudentByCourseId((long) courseId);
                    List<Long> studentIds = studentList.stream().map(Student::getUserId).collect(Collectors.toList());
                    SignInTask signInTask = new SignInTask(teacherId, taskName, studentIds, startTime, endTime, 1);
                    System.out.println("签到开始");
                    signInService.insertSignInTask(signInTask);
                    Thread thread = new Thread(() -> {
                        try {
                            Thread.sleep(second*1000);
                            signInService.updateStateToClosed(teacherId);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    });
                    thread.start();
                }break;
                case "8":{
                    System.out.println("8.退出");
                    cur = false;
                };break;
                case "9":{
                    scanner.nextLine();
                    System.out.println("需要进行身份校验, 请选择验证方式");
                    System.out.println("1.密码校验");
                    System.out.println("2.手机号校验");
                    System.out.println("3.邮箱校验");
                    String sc = scanner.nextLine();
                    UpdatePasswordRequest updatePasswordRequest = new UpdatePasswordRequest();
                    switch (sc) {
                        case "1":{
                            System.out.println("请输入密码");
                            String oldPassword = scanner.nextLine();
                            updatePasswordRequest.setUserId(user.getUserId());
                            updatePasswordRequest.setOldPassword(oldPassword);
                            updatePasswordRequest.setUpdatePasswordState(UpdatePasswordState.Password);
                        }
                        break;
                        case "2":{
                            System.out.println("请输入手机号");
                            String phone = scanner.nextLine();
                            updatePasswordRequest.setUserId(user.getUserId());
                            updatePasswordRequest.setPhone(phone);
                            updatePasswordRequest.setUpdatePasswordState(UpdatePasswordState.Phone);
                        }
                        break;
                        case "3":{
                            System.out.println("请输入邮箱");
                            String email = scanner.nextLine();
                            updatePasswordRequest.setUserId(user.getUserId());
                            updatePasswordRequest.setEmail(email);
                            updatePasswordRequest.setUpdatePasswordState(UpdatePasswordState.Email);
                        }
                        break;
                        default:break;
                    }
                    UpdatePasswordContext updatePasswordContext = new UpdatePasswordContext();
                    updatePasswordContext.updatePassword(updatePasswordRequest);
                }
                break;
                default:
                    System.out.println("输入有误，请重新输入");
                    break;
            }
        }
    }

    /**
     * 打印学生信息
     * @param studentList
     */
    private static void printStudentDetails(List<StudentDetail> studentList) {
        if (studentList.isEmpty()) {
            System.err.println("暂时还没有学生选择这门课");
            return;
        }

        System.out.println("+-------+------------+------------+-------+-----------------+----------------------+-----------------+------------+-----------------+");
        System.out.println("|  ID   | STUDENT_ID | COURSE_ID  | SCORE | TEACHER_NAME    | COURSE_NAME          | STUDENT_NAME    | CLASS_ID   | CLASS_NAME      |");
        System.out.println("+-------+------------+------------+-------+-----------------+----------------------+-----------------+------------+-----------------+");

        studentList.forEach(student -> System.out.println("| " + student.toString() + " |"));

        System.out.println("+-------+------------+------------+-------+-----------------+----------------------+-----------------+------------+-----------------+");
    }

    /**
     * 打印课程列表表格格式
     *
     * @param courseList 课程列表
     */
    private static void printCourseList(List<Course> courseList) {


        // 打印表头
        System.out.println("+-----------------+-----------------+------------+");
        System.out.printf("| %-15s | %-15s | %-10s |%n", "TeacherName", "CourseName", "CourseId");
        System.out.println("+-----------------+-----------------+------------+");

        // 打印每门课程的信息
        for (Course course : courseList) {
            System.out.println(course.toString());
        }

        // 打印表尾
        System.out.println("+-----------------+-----------------+------------+");
    }


}
